// pages/index/index.js
import Util from "../../../utils/utils";
import User from "../../../utils/user";
let systemInfo = wx.getSystemInfoSync();
let winWidth = systemInfo.windowWidth;
let winHeight = systemInfo.windowHeight;
let ratio = systemInfo.pixelRatio;
let boxHeight = Util.rpxToPx(546);
let app = getApp();
Page({
  distance: '',
  channel: {},
  data: {
    x: winWidth,
    y: winHeight,
    imageHeight: winHeight - boxHeight,
    containerHeight: winHeight - 100,
    animationA: {},
    startX: '',
    startY: '',
    initUser: true,
    listPage: 1,
    listData: [],
    listMore: true,
    listEmpty: false,
    shareGoodsReturnBean: 0,
    isHideGuide: true // 是否隐藏指引
  },
  initPage: function() {
    let self = this;
    let setData = {};
    let systemInfo;
    wx.showTabBar();
    this.setData({
      shareGoodsReturnBean: app.globalData.pageConfig.sharePea,
    })
    if (!this.data.userInfo) {
      setData['uuid'] = Util.getUUID();
    } else {
      setData['uuid'] = '';
    }
    Util.log(boxHeight);
    systemInfo = wx.getSystemInfoSync();
    setData['y'] = systemInfo.windowHeight;
    setData['imageHeight'] = systemInfo.windowHeight - boxHeight;
    if (this.data.listData.length > 0) {
      return true;
    }
    self.channel = User.getShareParam(0);
    self.onTabItemTap();
    self.setData(setData);
    self.initGuide()
    self.initData();
    app.addEvent('upUserInfo', function(userInfo) {
      self.channel = User.getShareParam(0);
    });
  },
  initData: function() {
    let self = this;
    let param = {
      page: 1,
      page_size: 10,
      client_type: 3
    };
    if (self.data.uuid !== '') {
      param['vkey'] = self.data.uuid;
    }
    wx.showNavigationBarLoading();
    /**
     * 获取第一页数据
     */
    Util.request({
      url: Util.api.DiscountsList,
      data: param,
      error: function() {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      },
      callback: function(result) {
        let sData = {};
        let _data = self.formatData(result.res.recommend_list);
        let more = false;
        if (_data.length < result.res.total) {
          more = true;
        }
        _data = self.reverseData(_data);
        sData['listData'] = _data;
        sData['listPage'] = 1;
        sData['listEmpty'] = _data <= 0;
        sData['videoIndex'] = 0;
        sData['listMore'] = more;
        self.setData(sData);
        if (_data.length > 0) {
          self.setShareInfo(_data[_data.length - 1]);
        }
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  initGuide() {
    let isHideGuide = wx.getStorageSync('isHideViewGoodsGuide')
    if (!isHideGuide) {
      this.setData({
        isHideGuide: isHideGuide
      })
    }
  },
  onCloseGuide() {
    this.setData({
      isHideGuide: true
    })
    wx.setStorageSync('isHideViewGoodsGuide', true)
  },
  onTabItemTap: function() {
    Util.setVideoTabBar(1);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.initData();
  },
  touchStart(e) {
    let startX = e.touches[0].clientX;
    let startY = e.touches[0].clientY;
    this.setData({
      startX,
      startY
    })
  },
  // 拖动结束
  touchEnd(e) {
    let self = this;
    let startX = this.data.startX;
    let startY = this.data.startY;
    let endX = e.changedTouches[0].clientX;
    let endY = e.changedTouches[0].clientY;
    let distance = self.distance;
    // 与结束点与图片初始位置距离
    let disX = Math.abs(distance - winWidth);
    // 当前操作，初始点与结束点距离
    let disClientX = Math.abs(endX - startX);
    let disClientY = Math.abs(endY - startY);
    // 当滑动大于 滑块宽度的1/3翻页
    let moveDis = 666 / (ratio * 4);
    let listData = self.data.listData;
    let index = e.currentTarget.dataset.index;
    if (disX > moveDis && disClientX > moveDis) {
      try {
        listData[index].x = (endX - startX) > 0 ? winWidth * 2 : -winWidth;
        self.setData({
          listData: listData,
          animationA: null
        });
        // 移出动画结束后 从list内移除
        setTimeout(() => {
          let newList = [];
          for (let i = 0; i < listData.length; i++) {
            if (i !== index) {
              newList.push(listData[i]);
            }
          }
          self.setData({
            listData: newList
          });
          if (newList.length > 0) {
            self.setShareInfo(newList[newList.length - 1]);
          }
          // 列表长度小于4的时候请求服务端
          if (newList.length < 7) {
            self.getMore();
          }
        }, 100)
      } catch (e) {}
    } else if (disClientX < 1 && disClientY < 1) {
      // 点击进入
      let goodsInfo = listData[index]
      if (goodsInfo.platform_type === 4) {
        Util.toPage('/pages/goods/mmallGoodsDetails/mmallGoodsDetails?id=' + goodsInfo.goods_id);
      } else {
        Util.toPage('/pages/goods/detail/detail?id=' + goodsInfo.goods_id);
      }
    } else {
      listData[index].x = winWidth;
      listData[index].y = 0;
      self.setData({
        listData
      });
    }
  },
  onTouchmove: function(e) {
    let touch = e.touches[0];
    this.distance = touch.pageX;
  },
  getMore: function() {
    let self = this;
    if (self.data.listMore === true) {
      let param = {
        page: self.data.listPage + 1,
        page_size: 10,
        client_type: 3
      };
      if (self.data.uuid !== '') {
        param['vkey'] = self.data.uuid;
      }
      Util.request({
        url: Util.api.DiscountsList,
        data: param,
        loading: 2,
        callback: function(result) {
          let setData = {
            listPage: self.data.listPage + 1,
            listMore: false
          };
          let index = self.data.listData.length;
          let _data = self.formatData(result.res.recommend_list);
          let lData = self.reverseData(self.data.listData);
          let _total = result.res.total;
          let more = false;
          for (let i = 0; i < _data.length; i++) {
            lData.push(_data[i]);
          }
          if (lData.length < _total - 1) {
            more = true;
          }
          setData['listData'] = self.reverseData(lData);
          setData['listMore'] = more;
          self.setData(setData);
        }
      });
    } else {
      Util.msg('已经到底了，刷新试试吧！');
    }
  },
  formatData: function(list) {
    for (let i = 0; i < list.length; i++) {
      list[i] = list[i]['goods'];
      list[i]['index'] = i + 10;
      list[i]['x'] = winWidth;
      list[i]['y'] = 0;
      list[i]['discount_text'] = Util.formatMoney(list[i]['coupon_discount']);
      list[i]['originalPrice_text'] = Util.formatMoney(list[i]['price']);
      list[i]['price_text'] = Util.formatMoney(list[i]['lowestPrice']);
      list[i]['start_date'] = Util.formatTime('yyyy.MM.dd', list[i]['coupon_start_time']);
      list[i]['end_date'] = Util.formatTime('yyyy.MM.dd', list[i]['coupon_end_time']);
    }
    return list;
  },
  setShareInfo: function(goods) {
    let self = this
    let shareTitle = '';
    let sharePath = '/pages/goods/detail/detail';
    this.setData({
      goodsID: goods.goods_id
    });
    if (!goods) {
      this.shareOption['path'] = '';
      return false;
    }
    sharePath += '?id=' + goods['goods_id'];
    if (this.channel.ekey) {
      sharePath += '&ekey=' + this.channel.ekey;
    }
    if (this.channel.shareUid > 0) {
      sharePath += '&uid=' + this.channel.shareUid;
    }
    /**
     * 设置分享信息
     */
    shareTitle = "【" + (goods.platform === 3 ? '京东' : '拼多多') + "】";
    if (goods.discount > 0) {
      shareTitle += '优惠券' + goods['discount_text'] + "元，";
    }
    if (goods['price_text'] !== goods['originalPrice_text']) {
      shareTitle += '原价' + goods['originalPrice_text'] + '元，券后' + goods['price_text'] + '元';
    } else {
      shareTitle += '惊爆价' + goods['originalPrice_text'] + '元';
    }
    this.shareOption['title'] = shareTitle;
    this.shareOption['imageUrl'] = goods.goodsImage;
    this.shareOption['path'] = sharePath;

    Util.request({
      url: '/wxgroup/WxGoodsPoster',
      data: {
        "goods_id": goods['goods_id'],
      },
      loading: 2,
      handle: true,
      callback: function(result) {
        console.log(result)
        self.shareOption['imageUrl'] = result['res'];
      }
    });

  },
  reverseData: function(list) {
    let newSet = [];
    for (let i = list.length - 1; i >= 0; i--) {
      newSet.push(list[i]);
    }
    return newSet;
  },
  receiveBtn: function() {
    Util.toPage('/pages/goods/detail/detail?id=' + this.data.goodsID);
  }
});